# get facebook payload by devices
# get all facebook payloads

# the task to get all http records

require "00_common"


# INPUT_DIR = "./sampledata/"
INPUT_DIR   = "./facebook_payload_with_cookie/"
OUTPUT_DIR  = "./facebook_mobile/"
#OUTPUT_DIR  = "./facebook_android/"

module GetFacebookLaptop
  def self.run
    puts ">> start to get http records..."

    begin
      all_files = GetFacebookLaptop.get_all_files

      GetFacebookLaptop.handle_all_files all_files

      puts ">> end to get http records."
    rescue Exception => e
      puts ">> EEROR:"
      puts e.to_s
    end
  end


  def self.get_all_files
    Common.get_all_files(INPUT_DIR)
  end

  def self.handle_all_files(all_files)
    all_files.each do |file_name|
      new_file_name = Common.alternate_file_name(file_name, "_payload_", "_mobile_")
      if Common.file_exist?(OUTPUT_DIR,new_file_name)
        puts "exist file:" + new_file_name
      else
        handle_each_file(file_name)
        Common.move_file new_file_name, OUTPUT_DIR
      end
    end
  end
 

  def self.handle_each_file(file_name)
    puts "now handling : " + file_name
    file = File.open INPUT_DIR + file_name, "r"
    output_file_name = Common.alternate_file_name(file_name, "_payload_", "_mobile_") 
    output_file = File.open output_file_name, "w"

    begin
      counter = 0
      while line = file.readline

        if line.start_with? "#"
          next
        end

        counter = counter + 1

        line = line.rstrip
        if line.end_with? "|"
          line = line + "NULL"
        end
        fields = line.split "|"
        
        user_agent = fields[11].downcase

        # if user_agent.include? "windows nt" or user_agent.include? "max os x"
        if user_agent.include? "webos" or user_agent.include? "android"
          output_file.puts line
        end

      end
    rescue Exception => e
      puts e.to_s
      file.close
    end

    output_file.close
  end

end